<template>
  <div class="articles-container">
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">添加文章</el-button>
    </div>
    <el-table :data="articles" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="categoryName" label="分类" width="120" />
      <el-table-column prop="viewCount" label="浏览量" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">{{ formatDate(row.createTime) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑文章' : '添加文章'" width="70%">
      <el-form :model="form" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option 
              v-for="item in categories" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <el-input 
            v-model="form.content" 
            type="textarea" 
            :rows="10" 
            placeholder="支持Markdown格式" />
        </el-form-item>
        <el-form-item label="摘要">
          <el-input v-model="form.summary" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="置顶">
          <el-switch v-model="form.isTop" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getArticleList, getArticleDetail, createArticle, updateArticle, deleteArticle } from '@/api/article'
import { getCategoryList } from '@/api/category'
import { getCurrentUser } from '@/api/auth'

const articles = ref([])
const categories = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const userInfo = ref({})

const form = reactive({
  id: null,
  title: '',
  content: '',
  summary: '',
  categoryId: '',
  isTop: false,
  userId: null
})

const fetchArticles = async () => {
  try {
    const res = await getArticleList()
    articles.value = res.data
  } catch (error) {
    console.error('获取文章列表失败:', error)
  }
}

const fetchCategories = async () => {
  try {
    const res = await getCategoryList()
    categories.value = res.data
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

const resetForm = () => {
  form.id = null
  form.title = ''
  form.content = ''
  form.summary = ''
  form.categoryId = ''
  form.isTop = false
}

const handleAdd = () => {
  resetForm()
  form.userId = userInfo.value.userId
  isEdit.value = false
  dialogVisible.value = true
}

const handleEdit = async (row) => {
  try {
    const res = await getArticleDetail(row.id)
    const article = res.data
    form.id = article.id
    form.title = article.title
    form.content = article.content
    form.summary = article.summary
    form.categoryId = article.categoryId
    form.isTop = article.isTop === 1
    form.userId = article.userId
    isEdit.value = true
    dialogVisible.value = true
  } catch (error) {
    console.error('获取文章详情失败:', error)
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该文章？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteArticle(row.id)
      ElMessage.success('删除成功')
      fetchArticles()
    } catch (error) {
      console.error('删除文章失败:', error)
    }
  }).catch(() => {})
}

const submitForm = async () => {
  try {
    // 处理置顶状态
    form.isTop = form.isTop ? 1 : 0
    
    if (isEdit.value) {
      await updateArticle(form)
      ElMessage.success('更新成功')
    } else {
      await createArticle(form)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchArticles()
  } catch (error) {
    console.error('保存文章失败:', error)
  }
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
}

onMounted(() => {
  userInfo.value = getCurrentUser()
  fetchArticles()
  fetchCategories()
})
</script>

<style scoped>
.articles-container {
  padding: 20px;
}
.toolbar {
  margin-bottom: 20px;
}
</style>